<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    wrapClassName="modal-add"
    destroyOnClose
  >
    <BasicForm @register="registerForm"> </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref, h, reactive, watch } from 'vue'
  import { BasicModal, useModalInner } from '@/components/Modal'
  import { BasicForm, useForm } from '@/components/Form'
  import { addRecordPrice, updateRecordPrice } from '@/api/sys/energyUnitPrice'
  import dayjs from 'dayjs'
  import { message } from 'ant-design-vue'

  defineOptions({ name: 'ModalAddGroup' })

  const emit = defineEmits(['success', 'register'])

  const isUpdate = ref(false)
  const currentData = ref()
  const groupIndex = ref()
  const groupData = ref([])

  const validName = (rule, value, callback) => {
    let tagNames = groupData.value.map((item) => item.tag)

    if (isUpdate.value) {
      const currentName = currentData.value.tag
      tagNames = tagNames.filter((item) => item !== currentName)
    }

    return new Promise((resolve, reject) => {
      if (tagNames.includes(value)) {
        reject(new Error('已有重复分段名'))
      } else {
        resolve()
      }
    })
  }

  // 分段弹窗
  const addGroupFormSchema: FormSchema[] = [
    {
      field: 'tag',
      label: '分段名',
      component: 'Input',
      rules: [
        {
          required: true,
          validator: validName,
        },
      ],
    },
    {
      field: 'price',
      label: '分段价格',
      component: 'InputNumber',
      rules: [
        {
          required: true,
        },
      ],
    },
  ]

  const [
    registerForm,
    { setFieldsValue, getFieldsValue, validateFields, updateSchema, resetFields, validate },
  ] = useForm({
    labelWidth: 140,
    baseColProps: { span: 24 },
    schemas: addGroupFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  })

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields()
    setModalProps({ confirmLoading: false })
    isUpdate.value = !!data?.isUpdate
    groupData.value = data.groupData

    if (unref(isUpdate)) {
      currentData.value = data.data
      groupIndex.value = data.index
      setFieldsValue({
        ...data.data,
      })
    }
  })

  const getTitle = computed(() => (!unref(isUpdate) ? '新增分段' : '修改分段'))

  async function handleSubmit() {
    try {
      const values = await validate()
      let data = { values }
      if (unref(isUpdate)) {
        data = { ...data, groupIndex: unref(groupIndex) }
      }
      setModalProps({ confirmLoading: true })
      message.success(isUpdate.value ? '修改成功' : '添加成功')
      closeModal()
      emit('success', { isUpdate: unref(isUpdate), data })
    } finally {
      setModalProps({ confirmLoading: false })
    }
  }
</script>
